//
//  WJCalendarVC.m
//  Imagedemo
//
//  Created by 文杰 许                       on 2018/4/13.
//  Copyright © 2018年 文杰 许                      . All rights reserved.
//

#import "WJCalendarVC.h"
#import "JTCalendar.h"
#import "JTCalendarMenuView.h"
#import "JTCalendarContentView.h"
@interface WJCalendarVC ()<JTCalendarDataSource>
@property (nonatomic, strong) JTCalendarMenuView *calendarMenuView;
@property (nonatomic, strong) JTCalendarContentView *calendarContentView;
@property (nonatomic, strong) JTCalendar *calendar;
@end

@implementation WJCalendarVC
{
    NSMutableDictionary *eventsByDate;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self initSubViews];
    
    self.calendar = [JTCalendar new];
    
    // All modifications on calendarAppearance have to be done before setMenuMonthsView and setContentView
    // Or you will have to call reloadAppearance
    {
        self.calendar.calendarAppearance.calendar.firstWeekday = 2; // Sunday == 1, Saturday == 7
        self.calendar.calendarAppearance.dayCircleRatio = 9. / 10.;
        self.calendar.calendarAppearance.ratioContentMenu = 2.;
        self.calendar.calendarAppearance.focusSelectedDayChangeMode = YES;
        
        // Customize the text for each month
        self.calendar.calendarAppearance.monthBlock = ^NSString *(NSDate *date, JTCalendar *jt_calendar){
            NSCalendar *calendar = jt_calendar.calendarAppearance.calendar;
            NSDateComponents *comps = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth fromDate:date];
            NSInteger currentMonthIndex = comps.month;
            
            static NSDateFormatter *dateFormatter;
            if(!dateFormatter){
                dateFormatter = [NSDateFormatter new];
                dateFormatter.timeZone = jt_calendar.calendarAppearance.calendar.timeZone;
            }
            
            while(currentMonthIndex <= 0){
                currentMonthIndex += 12;
            }
            
            // NSString *monthText = [[dateFormatter standaloneMonthSymbols][currentMonthIndex - 1] capitalizedString];
            
            return [NSString stringWithFormat:@"%ld\n%ld月", comps.year, (long)currentMonthIndex];
        };
    }
    
    [self.calendar setMenuMonthsView:self.calendarMenuView];
    [self.calendar setContentView:self.calendarContentView];
    [self.calendar setDataSource:self];
    
    [self createRandomEvents];
    
    [self.calendar reloadData];
}

- (void)initSubViews
{
    self.calendarMenuView = [[JTCalendarMenuView alloc] initWithFrame:RECT(0, 64, SCREEN_WIDTH, 50)];
    [self.view addSubview:self.calendarMenuView];
    
    self.calendarContentView = [[JTCalendarContentView alloc] initWithFrame:RECT(0, CGRectGetMaxY(self.calendarMenuView.frame), SCREEN_WIDTH, 300)];
    [self.view addSubview:self.calendarContentView];
    
    UIButton *today = [UIButton buttonWithType:UIButtonTypeCustom];
    today.frame = RECT(50, CGRectGetMaxY(self.calendarContentView.frame) + 50, 50, 30);
    [today setTitle:@"today" forState:UIControlStateNormal];
    [today setTitleColor:KCOLOR_RED forState:UIControlStateNormal];
    [today addTarget:self action:@selector(today) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:today];
    
    UIButton *changeMode = [UIButton buttonWithType:UIButtonTypeCustom];
    changeMode.frame = RECT(200, CGRectGetMaxY(self.calendarContentView.frame) + 50, 100, 30);
    [changeMode setTitle:@"changeMode" forState:UIControlStateNormal];
    [changeMode setTitleColor:KCOLOR_RED forState:UIControlStateNormal];
    [changeMode addTarget:self action:@selector(changeMode) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:changeMode];
}

- (void)viewDidLayoutSubviews
{
    [self.calendar repositionViews];
}

- (void)today
{
    [self.calendar setCurrentDate:[NSDate date]];
}

- (void)changeMode
{
    self.calendar.calendarAppearance.isWeekMode = !self.calendar.calendarAppearance.isWeekMode;
    
    [self transitionExample];
}

#pragma mark - JTCalendarDataSource

- (BOOL)calendarHaveEvent:(JTCalendar *)calendar date:(NSDate *)date
{
    NSString *key = [[self dateFormatter] stringFromDate:date];
    
    if(eventsByDate[key] && [eventsByDate[key] count] > 0){
        return YES;
    }
    
    return NO;
}

- (void)calendarDidDateSelected:(JTCalendar *)calendar date:(NSDate *)date
{
    NSString *key = [[self dateFormatter] stringFromDate:date];
    NSArray *events = eventsByDate[key];
    
    NSLog(@"Date: %@ - %ld events", date, [events count]);
}

- (void)calendarDidLoadPreviousPage
{
    NSLog(@"Previous page loaded");
}

- (void)calendarDidLoadNextPage
{
    NSLog(@"Next page loaded");
}

#pragma mark - Transition examples

- (void)transitionExample
{
    CGFloat newHeight = 300;
    if(self.calendar.calendarAppearance.isWeekMode){
        newHeight = 75.;
    }
    
    [UIView animateWithDuration:.5
                     animations:^{
                         self.calendarContentView.frame = RECT(0, CGRectGetMaxY(self.calendarMenuView.frame), SCREEN_WIDTH, newHeight);
                         [self.view layoutIfNeeded];
                     }];
    
    [UIView animateWithDuration:.25
                     animations:^{
                         self.calendarContentView.layer.opacity = 0;
                     }
                     completion:^(BOOL finished) {
                         [self.calendar reloadAppearance];
                         
                         [UIView animateWithDuration:.25
                                          animations:^{
                                              self.calendarContentView.layer.opacity = 1;
                                          }];
                     }];
}

#pragma mark - Fake data

- (NSDateFormatter *)dateFormatter
{
    static NSDateFormatter *dateFormatter;
    if(!dateFormatter){
        dateFormatter = [NSDateFormatter new];
        dateFormatter.dateFormat = @"dd-MM-yyyy";
    }
    
    return dateFormatter;
}

- (void)createRandomEvents
{
    eventsByDate = [NSMutableDictionary new];
    
    for(int i = 0; i < 30; ++i){
        // Generate 30 random dates between now and 60 days later
        NSDate *randomDate = [NSDate dateWithTimeInterval:(rand() % (3600 * 24 * 60)) sinceDate:[NSDate date]];
        
        // Use the date as key for eventsByDate
        NSString *key = [[self dateFormatter] stringFromDate:randomDate];
        
        if(!eventsByDate[key]){
            eventsByDate[key] = [NSMutableArray new];
        }
        
        [eventsByDate[key] addObject:randomDate];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

@end
